﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Globalization;

namespace MultiViewer.Display
{
    /// <summary>
    /// Interaction logic for TraceViewer.xaml
    /// </summary>
    public partial class TraceViewer : UserControl
    {
        public delegate void SyncWriter();

        public class VisualTraceListener : TraceListener
        {
            private TraceViewer viewer = null;

            public VisualTraceListener(TraceViewer viewer)
            {
                this.viewer = viewer;
            }

            public override void Write(string message)
            {
                viewer.Dispatcher.BeginInvoke(new SyncWriter(delegate()
                {
                    TraceMessage msg = new TraceMessage(message);
                    viewer.listView.Items.Add(msg);
                    viewer.listView.ScrollIntoView(msg);
                }));
            }

            public override void WriteLine(string message)
            {
                viewer.Dispatcher.BeginInvoke(new SyncWriter(delegate()
                {
                    TraceMessage msg = new TraceMessage(message);
                    viewer.listView.Items.Add(msg);
                    viewer.listView.ScrollIntoView(msg);
                }));
            }
        }

        private VisualTraceListener listener = null;

        public TraceViewer()
        {
            InitializeComponent();
        }

        public TraceListener Listener
        {
            get
            {
                if (listener == null)
                    listener = new VisualTraceListener(this);
                return listener;
            }
        }
    }

    public class TraceMessage
    {
        private string time;
        private string message;

        public TraceMessage(string message)
        {
            time = DateTime.Now.ToString("hh:mm:ss", CultureInfo.InvariantCulture);
            this.message = message;
        }

        public string Time
        {
            get { return time; }
        }

        public string Message
        {
            get { return message; }
        }
    }
}
